package ventureco.gui;


import gov.nasa.worldwind.Configuration;
import gov.nasa.worldwind.avlist.AVKey;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.LayoutManager;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore.LoadStoreParameter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.event.MouseInputAdapter;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import sim.app.networktest.NetworkTestWithUI;
import ventureco.agent.Agent;
import ventureco.agent.AgentImpl;
import ventureco.map.MapBase;
import ventureco.map.MapImpl.AppFrame;

 
public class menu extends JPanel
implements ActionListener, ItemListener, MouseListener, MouseMotionListener {

protected JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, bt1, bt2, bt3, bt4, bt5, bt6;
protected JButton bt7, bt8, bt9;
public static boolean resumed = false;
JTextField text1,text2,text3,text4,text5,text6,text7;
JLabel agentLabel,jLabel1,jLabel2,jLabel3,jLabel4,jLabel5,jLabel6,jLabel7,jLabel8,jLabel9,jLabel10;
JCheckBox checkbox, checkbox2, checkbox3, checkbox4, checkbox5, checkbox6;
boolean box1 = false, box2 = false, box3 = false, box4 = false, box5 = false, box6 = false;
JToolBar toolBar = new JToolBar("menu");
JFrame frame2, frame3, frame4;
static JFrame frame;
protected JTextArea textArea,textArea2;
protected JTextField textField;
JFileChooser fc;
int id_count = 0;
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
    ImageIcon Button4Icon = new ImageIcon("images/save.png");
    ImageIcon Button5Icon = new ImageIcon("images/load.png");
    JScrollPane scrollPane2;
    int agentNumber = 0;
    JPanel panel,panel2,consolePanel;
    int posx,posy,dropx,dropy;
    static boolean simulationStarted = false;
	static Agent agent = new AgentImpl();
	long startTime;
	Calendar cal;
    
    public JMenuBar createMenuBar() {
    	Font font = new Font("Font",Font.BOLD,20);
        JMenuBar menuBar = new JMenuBar();
        menuBar.setBounds(800, 510, 200, 200);
        menuBar.setFont(font);
        menuBar.add(createMenu(" SAVE "));
        menuBar.add(createMenu(" LOAD "));
        menuBar.setBorder(BorderFactory.createMatteBorder(0,0,0,0,
                                                          Color.BLACK));
        return menuBar;
    }

    public JMenu createMenu(String title) {
    	Font font = new Font("Font",Font.BOLD,20);
        JMenu m = new HorizontalMenu(title);
        m.setFont(font);
    	if(title.equals(" SAVE ")) {
    	bt4 = new JButton("Save Agents",Button4Icon);
        bt4.setVerticalTextPosition(AbstractButton.BOTTOM);
        bt4.setHorizontalTextPosition(AbstractButton.CENTER);
        bt4.setMnemonic(KeyEvent.VK_D);
        bt4.setActionCommand("enable");
        
        bt5 = new JButton("Save Simulation",Button4Icon);
        bt5.setVerticalTextPosition(AbstractButton.BOTTOM);
        bt5.setHorizontalTextPosition(AbstractButton.CENTER);
        bt5.setMnemonic(KeyEvent.VK_D);
        bt5.setActionCommand("enable");
        
        bt6 = new JButton("Save Map",Button4Icon);
        bt6.setVerticalTextPosition(AbstractButton.BOTTOM);
        bt6.setHorizontalTextPosition(AbstractButton.CENTER);
        bt6.setMnemonic(KeyEvent.VK_D);
        bt6.setActionCommand("enable");
        
        m.add(bt4);
        m.add(bt5);
        m.add(bt6);
        
        bt4.addActionListener(this);
        bt5.addActionListener(this);
        bt6.addActionListener(this);
        
    	}
        
    	else {
    	       	bt7 = new JButton("Load Agents",Button5Icon);
    	        bt7.setVerticalTextPosition(AbstractButton.BOTTOM);
    	        bt7.setHorizontalTextPosition(AbstractButton.CENTER);
    	        bt7.setMnemonic(KeyEvent.VK_D);
    	        bt7.setActionCommand("enable");
    	        
    	        bt8 = new JButton("Load Simulation",Button5Icon);
    	        bt8.setVerticalTextPosition(AbstractButton.BOTTOM);
    	        bt8.setHorizontalTextPosition(AbstractButton.CENTER);
    	        bt8.setMnemonic(KeyEvent.VK_D);
    	        bt8.setActionCommand("enable");
    	        
    	        bt9 = new JButton("Load Map",Button5Icon);
    	        bt9.setVerticalTextPosition(AbstractButton.BOTTOM);
    	        bt9.setHorizontalTextPosition(AbstractButton.CENTER);
    	        bt9.setMnemonic(KeyEvent.VK_D);
    	        bt9.setActionCommand("enable");
    	        
    	        m.add(bt7);
    	        m.add(bt8);
    	        m.add(bt9);
    	        
    	        bt7.addActionListener(this);
    	        bt8.addActionListener(this);
    	        bt9.addActionListener(this);
    	}
        

        /*JMenu submenu = new HorizontalMenu("Submenu");
        submenu.add("Submenu item #1");
        submenu.add("Submenu item #2");
        m.add(submenu);*/

        return m;
    }

    class HorizontalMenu extends JMenu {
        HorizontalMenu(String label) {
            super(label);
            JPopupMenu pm = getPopupMenu();
            pm.setLayout((LayoutManager) new BoxLayout(pm, BoxLayout.LINE_AXIS));
        }

        public Dimension getMinimumSize() {
            return getPreferredSize();
        }

        public Dimension getMaximumSize() {
            return getPreferredSize();
        }

        public void setPopupMenuVisible(boolean b) {
            boolean isVisible = isPopupMenuVisible();
            if (b != isVisible) {
                if ((b==true) && isShowing()) {
                    int x = 0;
                    int y = 0;
                    Container parent = getParent();
                    if (parent instanceof JPopupMenu) {
                        x = 0;
                        y = getHeight();
                    } else {
                        x = getWidth();
                        y = 0;
                    }
                    getPopupMenu().show(this, x, y);
                } else {
                    getPopupMenu().setVisible(false);
                }
            }
        }
    }

 
    public menu() {
     	Font font = new Font("baso", Font.BOLD, 16);
     	Font font2 = new Font("baso2", Font.ITALIC, 17);
        addButtons(toolBar);
        textArea = new JTextArea(40, 5);
        textArea.setBackground(Color.LIGHT_GRAY);
        textArea.setEditable(false);
        //textArea.setDragEnabled(true);
		panel2 = new JPanel();
		panel2.setBounds(20, 100, 150, 400);
		consolePanel = new JPanel();
		// EKLENDI
        b10 = new JButton(" Show Agents' Batteries ");
        b10.setVerticalTextPosition(AbstractButton.BOTTOM);
        b10.setHorizontalTextPosition(AbstractButton.CENTER);
        b10.setMnemonic(KeyEvent.VK_D);
        b10.setActionCommand("enable");
        
        b10.setBounds(20,550, 200,40);
        add(b10);
        b10.addActionListener(this);
		//
		addMouseMotionListener(this);
        
	    /*JComboBox SaveList = new JComboBox(Savestr);
        SaveList.setSelectedIndex(2);
        SaveList.addActionListener(this);
        add(SaveList);
        bt4 = new JButton("Save Simulation");
        bt4.setVerticalTextPosition(AbstractButton.BOTTOM);
        bt4.setHorizontalTextPosition(AbstractButton.CENTER);
        bt4.setMnemonic(KeyEvent.VK_D);
        bt4.setActionCommand("enable");*/
        //popup.add(bt4);
        
        //setPreferredSize(new Dimension(450, 130));
        //add(toolBar, BorderLayout.PAGE_START);
        //panel.add(textArea);
        setLayout(null);
		consolePanel.setBounds(830, 100, 150, 400);
		//consolePanel.add(timer);
        jLabel7 = new JLabel("ADDED AGENTS");
        jLabel7.setFont(font);
        jLabel7.setBounds(30, 80, 150, 20);
        panel2.add(jLabel7);
        panel = new JPanel();
        panel.setBounds(200,100,600,400);
        add(panel);
        add(panel2);
        add(consolePanel);
        toolBar.setBounds(50, 10, 850, 60);
        jLabel9 = new JLabel("-PREVIEW OF SELECTED MAP-");
        jLabel9.setFont(font2);
        jLabel9.setBounds(350, 80, 300, 20);
        add(jLabel9);
        
    }

    
    private class DragMouseAdapter extends MouseInputAdapter {
        public void mousePressed(MouseEvent e) {
          JComponent c = (JComponent) e.getSource();
          TransferHandler handler = c.getTransferHandler();
          handler.exportAsDrag(c, e, TransferHandler.COPY);
          //JOptionPane.showMessageDialog(null, e.toString());
        }
        public void mouseReleased (MouseEvent e) {
            int x = e.getPoint().x;
            int y = e.getPoint().y;
            JOptionPane.showMessageDialog(null, x+" "+y);
        }
      }
    
 
    private void addButtons(JToolBar toolBar2) {
        ImageIcon Button1Icon = new ImageIcon("images/start.png");
        ImageIcon Button2Icon = new ImageIcon("images/add.png");
        ImageIcon Button3Icon = new ImageIcon("images/settings.png");
        ImageIcon Button4Icon = new ImageIcon("images/save.png");
        ImageIcon Button5Icon = new ImageIcon("images/load.png");
        ImageIcon Button6Icon = new ImageIcon("images/exit.png");
        ImageIcon Button7Icon = new ImageIcon("images/area.png");
        ImageIcon Button8Icon = new ImageIcon("images/uavs.png");
        ImageIcon Button9Icon = new ImageIcon("images/uavs.png");
    	
        b1 = new JButton(" Start Simulation ", Button1Icon);
        b1.setVerticalTextPosition(AbstractButton.BOTTOM);
        b1.setHorizontalTextPosition(AbstractButton.CENTER);
        b1.setMnemonic(KeyEvent.VK_D);
        b1.setActionCommand("enable");
        //b1.setEnabled(false);
 
        b2 = new JButton("  Add Agent  ", Button2Icon);
        b2.setVerticalTextPosition(AbstractButton.BOTTOM);
        b2.setHorizontalTextPosition(AbstractButton.CENTER);
        b2.setMnemonic(KeyEvent.VK_M);
        b2.setActionCommand("enable");
 
        b3 = new JButton("  Settings  ", Button3Icon);
        b3.setVerticalTextPosition(AbstractButton.BOTTOM);
        b3.setHorizontalTextPosition(AbstractButton.CENTER);
        b3.setMnemonic(KeyEvent.VK_E);
        b3.setActionCommand("enable");
        
        b4 = new JButton("    Save    ", Button4Icon);
        b4.setVerticalTextPosition(AbstractButton.BOTTOM);
        b4.setHorizontalTextPosition(AbstractButton.CENTER);
        b4.setMnemonic(KeyEvent.VK_E);
        b4.setActionCommand("enable");
        //b4.setEnabled(true);
        
        b5 = new JButton("    Load    ", Button5Icon);
        b5.setVerticalTextPosition(AbstractButton.BOTTOM);
        b5.setHorizontalTextPosition(AbstractButton.CENTER);
        b5.setMnemonic(KeyEvent.VK_E);
        b5.setActionCommand("enable");
        
        b6 = new JButton("    Exit    ", Button6Icon);
        b6.setVerticalTextPosition(AbstractButton.BOTTOM);
        b6.setHorizontalTextPosition(AbstractButton.CENTER);
        b6.setMnemonic(KeyEvent.VK_E);
        b6.setActionCommand("enable");
        
        b7 = new JButton("  Select Area  ",Button7Icon);
        b7.setVerticalTextPosition(AbstractButton.BOTTOM);
        b7.setHorizontalTextPosition(AbstractButton.CENTER);
        b7.setMnemonic(KeyEvent.VK_M);
        b7.setActionCommand("enable");
        
        b8 = new JButton("  Show Agents  ",Button8Icon);
        b8.setVerticalTextPosition(AbstractButton.BOTTOM);
        b8.setHorizontalTextPosition(AbstractButton.CENTER);
        b8.setMnemonic(KeyEvent.VK_M);
        b8.setActionCommand("enable");
        
        b9 = new JButton(" UAV SELECTION ",Button9Icon);
        b9.setVerticalTextPosition(AbstractButton.BOTTOM);
        b9.setHorizontalTextPosition(AbstractButton.CENTER);
        b9.setMnemonic(KeyEvent.VK_M);
        b9.setActionCommand("enable");
        
        toolBar2.add(b1);
        toolBar2.add(b2);
        toolBar2.add(b3);
        toolBar2.add(b4);
        toolBar2.add(b5);
        toolBar2.add(b7);
        toolBar2.add(b8);
        toolBar2.add(b9);
        toolBar2.add(b6);

        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
        b4.addActionListener(this);
        b5.addActionListener(this);
        b6.addActionListener(this);
        b7.addActionListener(this);
        b8.addActionListener(this);
        b9.addActionListener(this);
 
        b1.setToolTipText("Click this button to start the simulation.");
        b2.setToolTipText("Click this button to add an agent.");
        b3.setToolTipText("Click this button to open settings.");
        b4.setToolTipText("Click this button to save the simulation or scenario.");
        b5.setToolTipText("Click this button to load simulation or scenario.");
        b6.setToolTipText("Click this button to exit the program.");
        b7.setToolTipText("Click this button to select the area to be scanned.");
        b8.setToolTipText("Click this button to see the added agents.");
        b9.setToolTipText("Click this button to add the specified UAVs");
         
        add(toolBar2);
	}
    
	public void actionPerformed(ActionEvent e) {
    	
		// START SIMULATION
    	if(e.getSource().equals(b1))
    	{

    		cal = Calendar.getInstance();
				new NetworkTestWithUI().createController();
    		if(simulationStarted == false) {
    			try {
					Runtime.getRuntime().exec("convert.bat");
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				simulationStarted = true;
    		startTime = cal.getTimeInMillis();
    		}
    	}
    	
    	else if (e.getSource().equals(bt6)) {
    		JOptionPane.showMessageDialog(null, "Map has been saved successfully!");
    	}
    	
    	else if (e.getSource().equals(bt5)){
    		
    		try {
				writeSimulation();
				JOptionPane.showMessageDialog(null, "Simulation has been saved successfully!");
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
    	}
    		
    	
    	else if (e.getSource().equals(bt9)) {
    		JOptionPane.showMessageDialog(null, "Map has been loaded successfully!");
    		BufferedImage myPicture;
    		try {
    			myPicture = ImageIO.read(new File("images/bg.png"));
        		JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
        		panel.add(picLabel);
                super.add(panel);
        		//panel.setLayout(null);
        		picLabel.setBounds(0, 0, 600, 400);
    		} catch (IOException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}

    	}
    	
    	
    	else if (e.getSource().equals(b10)) {
    		if(agent.getList().size() == 0) {
    			JOptionPane.showMessageDialog(null, "No Agents Added");
    		}
    		else {
    			if(simulationStarted) {
    			cal = Calendar.getInstance();
    			for(int i = 0; i<agent.getList().size();i++) {
    				double remtime = 0;
    				double rembat = agent.getList().get(i).getBatteryTime()*3600;
    				long thetime = (cal.getTimeInMillis() - startTime)/1000;
    				if(rembat-(thetime*10) >= 0) {
    				remtime = rembat-(thetime*10);
    				}
    				else {
    					remtime = 0;
    				}
    				double kaybederiz = remtime/36;
    				int temp = (int)kaybederiz;
    				kaybederiz = ((double)temp)/100;
    				agent.getList().get(i).setRemainingBattery(kaybederiz);
    			}
    			String times = "";
    			for(int i =0 ; i<agent.getList().size();i++) {
    				times += "Agent " + (i+1) + " ";
    				times += agent.getList().get(i).getRemainingBattery() + " % ";
    				double kaybederiz = (agent.getList().get(i).getRemainingBattery()/agent.getList().get(i).getBatteryTime())*10000;
    				int temp = (int)kaybederiz;
    				kaybederiz = ((double)temp)/100;
    				times += kaybederiz + "\n" ;
    			}
    			JOptionPane.showMessageDialog(null, times);
    		}
    			else {
        			String times = "";
    	   			for(int i =0 ; i<agent.getList().size();i++) {
        				times += "Agent " + (i+1) + " ";
        				times += agent.getList().get(i).getRemainingBattery() + " % 100\n";
    	   			}
        			JOptionPane.showMessageDialog(null, times);
    			}
    		}
    	}
    	else
    	if(e.getSource().equals(b4) || e.getSource().equals(bt4))
    	{
    		try {

    	        //SaveList.setBounds(100, 100, 100, 100);
    			fc = new JFileChooser();
    			 int returnVal = fc.showSaveDialog(menu.this);

    	            if (returnVal == JFileChooser.APPROVE_OPTION) {
    	                File file = fc.getSelectedFile();
    					writeAgentList();
    					JOptionPane.showMessageDialog(null, "Agent Saved Succesfully");
    	            }
    	            
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
    	}
    	
    	else if(e.getSource().equals(bt8)){
    		try {
    			resumed = true;
				readSimulation();
				JOptionPane.showMessageDialog(null, "Simulation Loaded Succesfully");
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
    	}
    	
    	else if(e.getSource().equals(b5) || e.getSource().equals(bt7))
    	{
    		Font font = new Font("baso3", Font.PLAIN, 16);
    		try {
    			fc = new JFileChooser();
    			int returnVal = fc.showOpenDialog(menu.this);
    		     
    				if (returnVal == JFileChooser.APPROVE_OPTION) {
    	                File file = fc.getSelectedFile();
    					JOptionPane.showMessageDialog(null, "Agent Loaded Succesfully");
    					readAgentList();
    					for(agentNumber=1;agentNumber<agent.getList().size();agentNumber++) {
    		                agentLabel = new JLabel(" Agent  " + agentNumber, SwingConstants.LEADING);
    		                agentLabel.setTransferHandler(new TransferHandler("text"));
    		                agentLabel.setFont(font);

    		                MouseListener listener = new DragMouseAdapter();
    		                agentLabel.addMouseListener(listener);
    		                
    		       			panel2.add(agentLabel);
    		    			super.add(panel2);
    		    			agentLabel.setBounds(30, 20+(30*(agentNumber-1)), 160, 30);
    		        		double temp=0;
    					}
    				}
    				
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
    	}
    	else
    	if(e.getSource().equals(b6)) {
    		JOptionPane optionPane = new JOptionPane(
    			    "DO you want to exit\n",
    			    JOptionPane.QUESTION_MESSAGE,
    			    JOptionPane.YES_NO_OPTION);
    		int confirmation = JOptionPane.showConfirmDialog(optionPane, "Do you want to exit");
    		if (confirmation == 0)
    		System.exit(ABORT);
    	}
    	
    	//SETTINGS
    	else if (e.getSource().equals(b3)) {
    		frame4 = new JFrame("SETTINGS");
    		frame4.pack();
            frame4.setVisible(true);
            frame4.setBounds(600, 200, 600, 500);
    	}
    	
    	//SELECTION
    	else if (e.getSource().equals(b9)) {
        	frame2 = new JFrame("UAV SELECTION");
            //Display the window.
            frame2.pack();
            frame2.setVisible(true);
            frame2.setBounds(700, 300, 500, 400);
            
    		checkbox = new JCheckBox("Qinetiq Zephyr");
    		checkbox.setMnemonic(KeyEvent.VK_C);
    		
    		checkbox2 = new JCheckBox("Boeing Condor");
    		checkbox.setMnemonic(KeyEvent.VK_C);
    		
    		checkbox3 = new JCheckBox("IAI Heron");
    		checkbox.setMnemonic(KeyEvent.VK_C);
    		
    		checkbox4 = new JCheckBox("General Atomics MQ-1 Predator");
    		checkbox.setMnemonic(KeyEvent.VK_C);
    		
    		checkbox5 = new JCheckBox("TAI Anka");
    		checkbox.setMnemonic(KeyEvent.VK_C);
    		
    		checkbox6 = new JCheckBox("AAI Corporation Aerosonde");
    		checkbox.setMnemonic(KeyEvent.VK_C);
    		
            bt1 = new JButton("Confirm");
            bt1.setVerticalTextPosition(AbstractButton.CENTER);
            bt1.setHorizontalTextPosition(AbstractButton.LEADING);
            bt1.setMnemonic(KeyEvent.VK_M);
            bt1.setActionCommand("enable");
            
            
            bt1.addActionListener(this);

    	    JPanel checkPanel = new JPanel(new GridLayout(0, 1));
            checkPanel.add(checkbox);
            checkPanel.add(checkbox2);
            checkPanel.add(checkbox3);
            checkPanel.add(checkbox4);
            checkPanel.add(checkbox5);
            checkPanel.add(checkbox6);
            
            checkPanel.add(bt1);
            frame2.add(checkPanel);
            
            checkbox.addItemListener(this);
            checkbox2.addItemListener(this);
            checkbox3.addItemListener(this);
            checkbox4.addItemListener(this);
            checkbox5.addItemListener(this);
            checkbox6.addItemListener(this);

    	}
    	//CONFIRM BUTTON
    	else if (e.getSource().equals(bt1)) {
			Font font = new Font("baso3", Font.PLAIN, 16);
    		Agent agent1 = new AgentImpl();
    		Agent agent2 = new AgentImpl();
    		Agent agent3 = new AgentImpl();
    		Agent agent4 = new AgentImpl();
    		Agent agent5 = new AgentImpl();
    		Agent agent6 = new AgentImpl();
    		Point pt = new Point();
    		pt.x = 0;
    		pt.y = 0;
    		if(box1) {
    			agent1.setBatteryTime(336);
    			agent1.setCommunicationRange(1200);
    			agent1.setCurrentPosition(pt);
    			agent1.setID(agentNumber+1);
    			agent1.setMaxHeight(7200);
    			agent1.setMaxVelocity(600);
    			agent1.setRemainingBattery(336);
    			agent1.setSightRange(1500);
    			agent.setList(agent1);
    			agentNumber++;
	                agentLabel = new JLabel(" Agent  " + agentNumber, SwingConstants.LEADING);
	                agentLabel.setTransferHandler(new TransferHandler("text"));
	                agentLabel.setFont(font);

	                MouseListener listener = new DragMouseAdapter();
	                agentLabel.addMouseListener(listener);
	                
	       			panel2.add(agentLabel);
	    			super.add(panel2);
	    			agentLabel.setBounds(30, 20+(30*(agentNumber-1)), 160, 30);
	        		double temp=0;
    		}
    		if(box2) {
    			agent2.setBatteryTime(58);
    			agent2.setCommunicationRange(1000);
    			agent2.setCurrentPosition(pt);
    			agent2.setID(agentNumber+1);
    			agent2.setMaxHeight(5000);
    			agent2.setMaxVelocity(370);
    			agent2.setRemainingBattery(58);
    			agent2.setSightRange(900);
    			agent.setList(agent2);
    			agentNumber++;
	                agentLabel = new JLabel(" Agent  " + agentNumber, SwingConstants.LEADING);
	                agentLabel.setTransferHandler(new TransferHandler("text"));
	                agentLabel.setFont(font);

	                MouseListener listener = new DragMouseAdapter();
	                agentLabel.addMouseListener(listener);
	                
	       			panel2.add(agentLabel);
	    			super.add(panel2);
	    			agentLabel.setBounds(30, 20+(30*(agentNumber-1)), 160, 30);
	        		double temp=0;
    		}
    		if(box3) {
    			agent3.setBatteryTime(52);
    			agent3.setCommunicationRange(400);
    			agent3.setCurrentPosition(pt);
    			agent3.setID(agentNumber+1);
    			agent3.setMaxHeight(3600);
    			agent3.setMaxVelocity(207);
    			agent3.setRemainingBattery(52);
    			agent3.setSightRange(200);
    			agent.setList(agent3);
    			agentNumber++;
	                agentLabel = new JLabel(" Agent  " + agentNumber, SwingConstants.LEADING);
	                agentLabel.setTransferHandler(new TransferHandler("text"));
	                agentLabel.setFont(font);

	                MouseListener listener = new DragMouseAdapter();
	                agentLabel.addMouseListener(listener);
	                
	       			panel2.add(agentLabel);
	    			super.add(panel2);
	    			agentLabel.setBounds(30, 20+(30*(agentNumber-1)), 160, 30);
	        		double temp=0;
    		}
    		if(box4) {
    			agent4.setBatteryTime(40);
    			agent4.setCommunicationRange(400);
    			agent4.setCurrentPosition(pt);
    			agent4.setID(agentNumber+1);
    			agent4.setMaxHeight(2300);
    			agent4.setMaxVelocity(217);
    			agent4.setRemainingBattery(40);
    			agent4.setSightRange(250);
    			agent.setList(agent4);
    			agentNumber++;
	                agentLabel = new JLabel(" Agent  " + agentNumber, SwingConstants.LEADING);
	                agentLabel.setTransferHandler(new TransferHandler("text"));
	                agentLabel.setFont(font);

	                MouseListener listener = new DragMouseAdapter();
	                agentLabel.addMouseListener(listener);
	                
	       			panel2.add(agentLabel);
	    			super.add(panel2);
	    			agentLabel.setBounds(30, 20+(30*(agentNumber-1)), 160, 30);
	        		double temp=0;
    		}
    		if(box5) {
    			agent5.setBatteryTime(24);
    			agent5.setCommunicationRange(260);
    			agent5.setCurrentPosition(pt);
    			agent5.setID(agentNumber+1);
    			agent5.setMaxHeight(1300);
    			agent5.setMaxVelocity(217);
    			agent5.setRemainingBattery(24);
    			agent5.setSightRange(200);
    			agent.setList(agent5);
    			agentNumber++;
	                agentLabel = new JLabel(" Agent  " + agentNumber, SwingConstants.LEADING);
	                agentLabel.setTransferHandler(new TransferHandler("text"));
	                agentLabel.setFont(font);

	                MouseListener listener = new DragMouseAdapter();
	                agentLabel.addMouseListener(listener);
	                
	       			panel2.add(agentLabel);
	    			super.add(panel2);
	    			agentLabel.setBounds(30, 20+(30*(agentNumber-1)), 160, 30);
	        		double temp=0;
    		}
    		if(box6) {
    			agent6.setBatteryTime(26);
    			agent6.setCommunicationRange(260);
    			agent6.setCurrentPosition(pt);
    			agent6.setID(agentNumber+1);
    			agent6.setMaxHeight(1680);
    			agent6.setMaxVelocity(140);
    			agent6.setRemainingBattery(26);
    			agent6.setSightRange(70);
    			agent.setList(agent6);
    			agentNumber++;
	                agentLabel = new JLabel(" Agent  " + agentNumber, SwingConstants.LEADING);
	                agentLabel.setTransferHandler(new TransferHandler("text"));
	                agentLabel.setFont(font);

	                MouseListener listener = new DragMouseAdapter();
	                agentLabel.addMouseListener(listener);
	                
	       			panel2.add(agentLabel);
	    			super.add(panel2);
	    			agentLabel.setBounds(30, 20+(30*(agentNumber-1)), 160, 30);
	        		double temp=0;
    		}
    		JOptionPane.showMessageDialog(null, "Agents Added Successfully");
    		box1 = false;
    		box2 = false;
    		box3 = false;
    		box4 = false;
    		box5 = false;
    		box6 = false;
    		frame2.setVisible(false);
    	}
    	
    	//ADD AGENT
    	else if (e.getSource().equals(b2)) {
    		jLabel1 = new JLabel();
    		jLabel2 = new JLabel();
    		jLabel3 = new JLabel();
    		jLabel4 = new JLabel();
    		jLabel5 = new JLabel();
    		jLabel6 = new JLabel();
    		try {
            	frame2 = new JFrame("ADD AGENT");
                //Display the window.
                frame2.pack();
                frame2.setVisible(true);
                frame2.setBounds(400, 100, 600, 560);
                JPanel checkPanel = new JPanel();
                checkPanel.setLayout(null);
                
                jLabel1.setText("Agent's communication range : ");
                text1 = new JTextField();
                text1.setBounds(380, 30, 150, 30);
                jLabel1.setBounds(50, 30, 300, 30);
                checkPanel.add(jLabel1);
                checkPanel.add(text1);
                
                jLabel2.setText("Agent's sight range : ");
                text2 = new JTextField();
                text2.setBounds(380, 90, 150, 30);
                jLabel2.setBounds(50, 90, 300, 30);
                checkPanel.add(jLabel2);
                checkPanel.add(text2);
                
                jLabel3.setText("Agent's maximum velocity : ");
                text3 = new JTextField();
                text3.setBounds(380, 150, 150, 30);
                jLabel3.setBounds(50, 150, 300, 30);
                checkPanel.add(jLabel3);
                checkPanel.add(text3);
                
                jLabel4.setText("Agent's maximum height : ");
                text4 = new JTextField();
                text4.setBounds(380, 210, 150, 30);
                jLabel4.setBounds(50, 210, 300, 30);
                checkPanel.add(jLabel4);
                checkPanel.add(text4);
                
                jLabel5.setText("Agent's battery lifetime : ");
                text5 = new JTextField();
                text5.setBounds(380, 270, 150, 30);
                jLabel5.setBounds(50, 270, 300, 30);
                checkPanel.add(jLabel5);
                checkPanel.add(text5);
                
                jLabel6.setText("Agent's initial position (x & y) : ");
                text6 = new JTextField();
                text6.setBounds(380, 330, 65, 30);
                text7 = new JTextField();
                text7.setBounds(465, 330, 65, 30);
                jLabel6.setBounds(50, 330, 300, 30);
                checkPanel.add(jLabel6);
                checkPanel.add(text6);
                checkPanel.add(text7);
                
                ImageIcon bt3Icon = new ImageIcon("images/accept.png");
                bt3 = new JButton("ADD AGENT",bt3Icon);
                bt3.setVerticalTextPosition(AbstractButton.CENTER);
                bt3.setHorizontalTextPosition(AbstractButton.LEADING);
                bt3.setMnemonic(KeyEvent.VK_E);
                bt3.setActionCommand("enable");
                bt3.setEnabled(true);
                bt3.setBounds(200, 390, 200, 100);
                checkPanel.add(bt3);
                bt3.addActionListener(this);
                
                frame2.add(checkPanel);
                
 
/*
    		temp = Double.parseDouble(JOptionPane.showInputDialog("Set agent's communication range(meters)"));
    		agent.setCommunicationRange(temp);
    		temp = Double.parseDouble(JOptionPane.showInputDialog("Set agent's sight range(meters)"));
    		agent.setSightRange(temp);
    		temp = Double.parseDouble(JOptionPane.showInputDialog("Set agent's maximum velocity(km/hour)"));
    		agent.setMaxVelocity(temp);
    		temp = Double.parseDouble(JOptionPane.showInputDialog("Set agent's maximum height it can reach(meters)"));
    		agent.setMaxHeight(temp);
    		temp = Double.parseDouble(JOptionPane.showInputDialog("Set agent's battery lifetime(hours)"));
    		agent.setBatteryTime(temp);
    		p.x = Integer.parseInt(JOptionPane.showInputDialog("Set agent's initial x position"));
    		p.y = Integer.parseInt(JOptionPane.showInputDialog("Set agent's initial y position"));
    		agent.setCurrentPosition(p);
    		agent.setList(agent);
    		JOptionPane.showMessageDialog(null,"AGENT #" + agent.getID() + " HAS BEEN ADDED SUCCESSFULLY WITH THIS PROPERTIES IN " + dateFormat.format(date) + "\n" 
    						+ "Communication Range = " + agent.getCommunicationRange() + " meters\n"
    						+ "Sight Range = " + agent.getSightRange() + " meters\n"
    						+ "Maximum Velocity = " + agent.getMaxVelocity() + " km/hour\n"
    						+ "Maximum Height = " + agent.getMaxHeight() + " meters\n"
    						+ "Batterylife = " + agent.getBatteryTime() + " hours\n"
    						+ "Current Position = (" + agent.getCurrentPosition().x + " , " + agent.getCurrentPosition().y + ")\n");

*/    	
		}
		catch (IllegalArgumentException e1) {
			//e1.printStackTrace();
			JOptionPane.showMessageDialog(null,"WRONG TYPE! PLEASE CHECK YOUR INPUT!");
		}
    }

	else if(e.getSource().equals(bt3)) {
		Font font = new Font("baso3", Font.PLAIN, 16);
        agentNumber++;
        agentLabel = new JLabel(" Agent  " + agentNumber, SwingConstants.LEADING);
        agentLabel.setTransferHandler(new TransferHandler("text"));
        agentLabel.setFont(font);
        MouseListener listener = new DragMouseAdapter();
        agentLabel.addMouseListener(listener);
			panel2.add(agentLabel);
			super.add(panel2);
			agentLabel.setBounds(30, 20+(30*(agentNumber-1)), 160, 30);
    		double temp=0;
    		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd   HH:mm:ss");
    		Date date = new Date();
    		Point p = new Point();
    		Agent agent = new AgentImpl();
    		temp = Double.parseDouble(text1.getText());
            	agent.setCommunicationRange(temp);
            	temp = Double.parseDouble(text2.getText());
            	agent.setSightRange(temp);
            	temp = Double.parseDouble(text3.getText());
            	agent.setMaxVelocity(temp);
           	temp = Double.parseDouble(text4.getText());
            	agent.setMaxHeight(temp);
            	temp = Double.parseDouble(text5.getText());
            	agent.setBatteryTime(temp);
            	p.x = Integer.parseInt(text6.getText());
            	p.y = Integer.parseInt(text7.getText());
            	agent.setCurrentPosition(p);
    		agent.setList(agent);
			agentLabel.setToolTipText("Communication Range = " + agent.getCommunicationRange() + " meters\n"
					+ "Sight Range = " + agent.getSightRange() + " meters\n"
					+ "Maximum Velocity = " + agent.getMaxVelocity() + " km/hour\n"
					+ "Maximum Height = " + agent.getMaxHeight() + " meters\n"
					+ "Batterylife = " + agent.getBatteryTime() + " hours\n"
					+ "Current Position = (" + agent.getCurrentPosition().x + " , " + agent.getCurrentPosition().y + ")\n");
            
            
       		JOptionPane.showMessageDialog(null,"AGENT #" + agent.getID() + " HAS BEEN ADDED SUCCESSFULLY WITH THIS PROPERTIES IN " + dateFormat.format(date) + "\n" 
					+ "Communication Range = " + agent.getCommunicationRange() + " meters\n"
					+ "Sight Range = " + agent.getSightRange() + " meters\n"
					+ "Maximum Velocity = " + agent.getMaxVelocity() + " km/hour\n"
					+ "Maximum Height = " + agent.getMaxHeight() + " meters\n"
					+ "Batterylife = " + agent.getBatteryTime() + " hours\n"
					+ "Current Position = (" + agent.getCurrentPosition().x + " , " + agent.getCurrentPosition().y + ")\n");
       		frame2.setVisible(false);
    	}

    	//SHOW AGENTS
    	else if (e.getSource().equals(b8)) {
    		Agent agent = new AgentImpl();
    		ArrayList<Agent> agents = new ArrayList<Agent>();
    		agents = agent.getList();
    		if (agents.isEmpty()) {
    			JOptionPane.showMessageDialog(null, "NO AGENTS ADDED YET!");
    		}
    		else {
    		String message="";
    		for(int i=0;i<agents.size();i++) {
        		message += "AGENT #" + i + "\n" 
    		+ "Communication Range = " + agents.get(i).getCommunicationRange() + " meters\n"
			+ "Sight Range = " + agents.get(i).getSightRange() + " meters\n"
			+ "Maximum Velocity = " + agents.get(i).getMaxVelocity() + " km/hour\n"
			+ "Maximum Height = " + agents.get(i).getMaxHeight() + " meters\n"
			+ "Batterylife = " + agents.get(i).getBatteryTime() + " hours\n\n\n"
			;
			//+ "Current Position = (" + agents.get(i).getCurrentPosition().x + " , " + agents.get(i).getCurrentPosition().y + ")\n\n\n";
    
    		}
    		JOptionPane.showMessageDialog(null, message);
    	}
    	}
    	//SELECT AREA
    	else if (e.getSource().equals(b7)) {
    		b1.setEnabled(true);
    		Runtime load = Runtime.getRuntime();
    		try{
    			//new MapFrame().setVisible(true);
    			 Configuration.setValue(AVKey.INITIAL_ALTITUDE, 1000d);
  		         Configuration.setValue(AVKey.INITIAL_LATITUDE, 37.7794d);
		         Configuration.setValue(AVKey.INITIAL_LONGITUDE, -122.4192d);
		         MapBase.start("Select Area To Patrol", AppFrame.class);
    		}
    		catch(Exception er){
    			System.out.println("mapframei yukleyemedi");
    			er.printStackTrace();
    		}
    		
    		
    		
//    		try {
//				load.exec("ApplicationTemplate.bat");
//			} catch (IOException e1) {
//		
//				e1.printStackTrace();
//			}
    	}
    }
    
    public void itemStateChanged(ItemEvent e) {
    	
    	if (e.getSource().equals(checkbox)) {
    		box1 = !box1;
    	}
    	if (e.getSource().equals(checkbox2)) {
    		box2 = !box2;
    	}
    	if (e.getSource().equals(checkbox3)) {
    		box3 = !box3;
    	}
    	if (e.getSource().equals(checkbox4)) {
    		box4 = !box4;
    	}
    	if (e.getSource().equals(checkbox5)) {
    		box5 = !box5;
    	}
    	if (e.getSource().equals(checkbox6)) {
    		box6 = !box6;
    	}
    }
 
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = menu.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
 
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {

        //Create and set up the window.
        frame = new JFrame("MULTI AGENT SIMULATION");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JFrame.setDefaultLookAndFeelDecorated(true);

        //Create and set up the content pane.
        menu newContentPane = new menu();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        Container contentPane = frame.getContentPane();
        contentPane.setBackground(Color.WHITE); //contrasting bg
        contentPane.add(newContentPane.createMenuBar(),
                        BorderLayout.LINE_START);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
        frame.setBounds(100, 0, 1000, 650);

    }
    
    public static void writeAgentList() throws Exception
    {
    	Agent a = new AgentImpl();
    	ArrayList<Agent> agents = a.getList();
    	XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    	XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream("Agents.xml"));
    	XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    	XMLEvent end = eventFactory.createDTD("\n");
    	StartDocument startDocument = eventFactory.createStartDocument();
    	eventWriter.add(startDocument);
    	eventWriter.add(end);
    	StartElement configStartElement = eventFactory.createStartElement("", "", "Agents_List");
    	StartElement agentStartElement = eventFactory.createStartElement("", "", "Agent");
    	EndElement agentEndElement = eventFactory.createEndElement("", "", "Agent");
    	eventWriter.add(configStartElement);
    	eventWriter.add(end);
    	
    	for(int i = 0;i<agents.size();i++)
    	{	
    		eventWriter.add(agentStartElement);
    		eventWriter.add(end);
    		createNode(eventWriter,"ID",Integer.toString(agents.get(i).getID()));
    		createNode(eventWriter,"CommunicationRange",Double.toString(agents.get(i).getCommunicationRange()));
    		createNode(eventWriter,"SightRange",Double.toString(agents.get(i).getSightRange()));
    		createNode(eventWriter,"MaxVelocity",Double.toString(agents.get(i).getMaxVelocity()));
    		createNode(eventWriter,"MaxHeight",Double.toString(agents.get(i).getMaxHeight()));
    		createNode(eventWriter,"MaxBatteryTime",Double.toString(agents.get(i).getBatteryTime()));
    		eventWriter.add(agentEndElement);
    		eventWriter.add(end);
    		
    	}
    	
    	eventWriter.add(eventFactory.createEndElement("", "", "Agents_List"));
    	eventWriter.add(end);
    	eventWriter.add(eventFactory.createEndDocument());
    	eventWriter.close();
    }
    
    public static void writeSimulation() throws Exception
    {
    	Agent a = new AgentImpl();
    	ArrayList<Agent> agents = a.getList();
    	XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    	XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream("Simulation.xml"));
    	XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    	XMLEvent end = eventFactory.createDTD("\n");
    	StartDocument startDocument = eventFactory.createStartDocument();
    	eventWriter.add(startDocument);
    	eventWriter.add(end);
    	StartElement configStartElement = eventFactory.createStartElement("", "", "Agents_List");
    	StartElement agentStartElement = eventFactory.createStartElement("", "", "Agent");
    	EndElement agentEndElement = eventFactory.createEndElement("", "", "Agent");
    	eventWriter.add(configStartElement);
    	eventWriter.add(end);
    	
    	for(int i = 0;i<agents.size();i++)
    	{	
    		eventWriter.add(agentStartElement);
    		eventWriter.add(end);
    		createNode(eventWriter,"ID",Integer.toString(agents.get(i).getID()));
    		createNode(eventWriter,"CommunicationRange",Double.toString(agents.get(i).getCommunicationRange()));
    		createNode(eventWriter,"SightRange",Double.toString(agents.get(i).getSightRange()));
    		createNode(eventWriter,"MaxVelocity",Double.toString(agents.get(i).getMaxVelocity()));
    		createNode(eventWriter,"MaxHeight",Double.toString(agents.get(i).getMaxHeight()));
    		createNode(eventWriter,"MaxBatteryTime",Double.toString(agents.get(i).getBatteryTime()));
    		createNode(eventWriter,"CurrentXCoordinate",Double.toString(sim.app.networktest.NetworkTest.nodes[i].getX()));
    		createNode(eventWriter,"CurrentYCoordinate",Double.toString(sim.app.networktest.NetworkTest.nodes[i].getY()));
    		eventWriter.add(agentEndElement);
    		eventWriter.add(end);
    		
    	}
    	
    	eventWriter.add(eventFactory.createEndElement("", "", "Agents_List"));
    	eventWriter.add(end);
    	eventWriter.add(eventFactory.createEndDocument());
    	eventWriter.close();
    }
    
    
    
    private static void createNode(XMLEventWriter eventWriter, String name,
			String value) throws XMLStreamException {

		XMLEventFactory eventFactory = XMLEventFactory.newInstance();
		XMLEvent end = eventFactory.createDTD("\n");
		XMLEvent tab = eventFactory.createDTD("\t");
		// Create Start node
		StartElement sElement = eventFactory.createStartElement("", "", name);
		eventWriter.add(tab);
		eventWriter.add(sElement);
		// Create Content
		Characters characters = eventFactory.createCharacters(value);
		eventWriter.add(characters);
		// Create End node
		EndElement eElement = eventFactory.createEndElement("", "", name);
		eventWriter.add(eElement);
		eventWriter.add(end);

	}

    
    /*
    createNode(eventWriter,"ID",Integer.toString(agents.get(i).getID()));
	createNode(eventWriter,"CommunicationRange",Double.toString(agents.get(i).getCommunicationRange()));
	createNode(eventWriter,"SightRange",Double.toString(agents.get(i).getSightRange()));
	createNode(eventWriter,"MaxVelocity",Double.toString(agents.get(i).getMaxVelocity()));
	createNode(eventWriter,"MaxHeight",Double.toString(agents.get(i).getMaxHeight()));
	createNode(eventWriter,"MaxBatteryTime",Double.toString(agents.get(i).getBatteryTime()));
    */
    
    public static void readSimulation() throws Exception
    {
    	System.out.println("*********READ SIMULATION STARTED**************");
    	try {
    		 
    		SAXParserFactory factory = SAXParserFactory.newInstance();
    		SAXParser saxParser = factory.newSAXParser();
    	 
    		DefaultHandler handler = new DefaultHandler() {
    	 
    		boolean agentBool = false;
    		boolean ID = false;
    		boolean CommunicationRange = false;
    		boolean SightRange = false;
    		boolean MaxVelocity = false;
    		boolean MaxHeight = false;
    		boolean MaxBatteryTime = false;
    		boolean CurrentXCoords = false;
    		boolean CurrentYCoords = false;
    	 
    		int index;
    		
    		public void startElement(String uri, String localName,String qName, 
    	                Attributes attributes) throws SAXException {
    	 
    			if (qName.equalsIgnoreCase("Agent"))
    			{
    				agentBool = true;
    				index = AgentImpl.agents.size();
    				AgentImpl.agents.add(new AgentImpl());
    				System.out.println("a new agent has been added.");
    				
    			}
    	 
    			if (qName.equalsIgnoreCase("ID")) {
    				ID = true;
    			}
    	 
    			if(qName.equalsIgnoreCase("CurrentXCoordinate")){
    				CurrentXCoords = true;
    			}
    				
    			if(qName.equalsIgnoreCase("CurrentYCoordinate")){
    				CurrentYCoords = true;
    			}
    			
    			if (qName.equalsIgnoreCase("CommunicationRange")) {
    				CommunicationRange = true;
    			}
    	 
    			if (qName.equalsIgnoreCase("SightRange")) {
    				SightRange = true;
    			}
    	 
    			if (qName.equalsIgnoreCase("MaxVelocity")) {
    				MaxVelocity = true;
    			}
    			
    			if (qName.equalsIgnoreCase("MaxHeight")) {
    				MaxHeight = true;
    			}
    			
    			if (qName.equalsIgnoreCase("MaxBatteryTime")) {
    				MaxBatteryTime = true;
    			}
    	 
    		}
    	 
    		public void endElement(String uri, String localName,
    			String qName) throws SAXException {
    	 
    			if(qName.equalsIgnoreCase("Agent"))
    			{
    				System.out.println("end of agent");
    			}
    				
    	 
    		}
    	 
    		public void characters(char ch[], int start, int length) throws SAXException {
    			
    			//AgentImpl agent = null;
    			if(agentBool)
    			{
    				System.out.println("start of agent");
    				agentBool = false;
    				
    			}
    			
    			if(CurrentXCoords)
    			{
    				
    				System.out.println("current x coord is : " + new String(ch,start,length));
    				CurrentXCoords = false;
    				//AgentImpl.agents.get(index).setCommunicationRange(Double.parseDouble(new String(ch,start,length)));
    				
    				AgentImpl.agents.get(index).setX(Double.parseDouble(new String(ch,start,length)));
    				//sim.app.networktest.NetworkTest.nodes[index].task.startingLocation.x = AgentImpl.agents.get(index).getX();
    				
    			}
    			
    			if(CurrentYCoords)
    			{
    				System.out.println("current y coord is : " + new String(ch,start,length));
    				CurrentYCoords = false;
    				//AgentImpl.agents.get(index).setCommunicationRange(Double.parseDouble(new String(ch,start,length)));
    				AgentImpl.agents.get(index).setY(Double.parseDouble(new String(ch,start,length)));
    				//sim.app.networktest.NetworkTest.nodes[index].task.startingLocation.y = AgentImpl.agents.get(index).getY();
    				
    			}
    			if (ID) {
    				System.out.println("id = " + new String(ch, start, length));
    				ID = false;
    				AgentImpl.agents.get(index).setID(Integer.parseInt(new String(ch, start, length)));
    			}
    			
    			if (CommunicationRange) {
    				System.out.println("comrange = " + new String(ch, start, length));
    				AgentImpl.agents.get(index).setCommunicationRange(Double.parseDouble(new String(ch,start,length)));
    				CommunicationRange = false;
    			}
    	 
    			if (SightRange) {
    				System.out.println("sightrange = " + new String(ch, start, length));
    				AgentImpl.agents.get(index).setSightRange(Double.parseDouble(new String(ch,start,length)));
    				SightRange = false;
    			}
    	 
    			if (MaxVelocity) {
    				System.out.println("maxvelocity = " + new String(ch, start, length));
    				AgentImpl.agents.get(index).setMaxVelocity(Double.parseDouble(new String(ch,start,length)));
    				MaxVelocity = false;
    			}
    			
    			if (MaxHeight) {
    				System.out.println("maxheight = " + new String(ch, start, length));
    				AgentImpl.agents.get(index).setMaxHeight(Double.parseDouble(new String(ch,start,length)));
    				MaxHeight = false;
    			}
    			
    			if (MaxBatteryTime) {
    				System.out.println("maxbattery = " + new String(ch, start, length));
    				AgentImpl.agents.get(index).setBatteryTime(Double.parseDouble(new String(ch,start,length)));
    				MaxBatteryTime = false;
    				//list.add(agent);
    			}
    	 
    		}
    	 
    	     };
    	 
    	       saxParser.parse("Simulation.xml", handler);
    	 
    	     } catch (Exception e) {
    	       e.printStackTrace();
    	     }
    	System.out.println("*********READ SIMULATION ENDED**************");
    	//return list;
    }
    
    
    public static void readAgentList() throws Exception
    {
    	try {
    		 
    		SAXParserFactory factory = SAXParserFactory.newInstance();
    		SAXParser saxParser = factory.newSAXParser();
    	 
    		DefaultHandler handler = new DefaultHandler() {
    	 
    		boolean agentBool = false;
    		boolean ID = false;
    		boolean CommunicationRange = false;
    		boolean SightRange = false;
    		boolean MaxVelocity = false;
    		boolean MaxHeight = false;
    		boolean MaxBatteryTime = false;
    	 
    		int index;
    		
    		public void startElement(String uri, String localName,String qName, 
    	                Attributes attributes) throws SAXException {
    	 
    			if (qName.equalsIgnoreCase("Agent"))
    			{
    				agentBool = true;
    				index = AgentImpl.agents.size();
    				AgentImpl.agents.add(new AgentImpl());
    				
    			}
    	 
    			if (qName.equalsIgnoreCase("ID")) {
    				ID = true;
    			}
    	 
    			if (qName.equalsIgnoreCase("CommunicationRange")) {
    				CommunicationRange = true;
    			}
    	 
    			if (qName.equalsIgnoreCase("SightRange")) {
    				SightRange = true;
    			}
    	 
    			if (qName.equalsIgnoreCase("MaxVelocity")) {
    				MaxVelocity = true;
    			}
    			
    			if (qName.equalsIgnoreCase("MaxHeight")) {
    				MaxHeight = true;
    			}
    			
    			if (qName.equalsIgnoreCase("MaxBatteryTime")) {
    				MaxBatteryTime = true;
    			}
    	 
    		}
    	 
    		public void endElement(String uri, String localName,
    			String qName) throws SAXException {
    	 
    			if(qName.equalsIgnoreCase("Agent"))
    			{
    				System.out.println("end of agent");
    			}
    				
    	 
    		}
    	 
    		public void characters(char ch[], int start, int length) throws SAXException {
    			
    			//AgentImpl agent = null;
    			if(agentBool)
    			{
    				System.out.println("start of agent");
    				agentBool = false;
    				
    			}
    			if (ID) {
    				System.out.println("id = " + new String(ch, start, length));
    				ID = false;
    				AgentImpl.agents.get(index).setID(Integer.parseInt(new String(ch, start, length)));
    			}
    			
    			if (CommunicationRange) {
    				System.out.println("comrange = " + new String(ch, start, length));
    				AgentImpl.agents.get(index).setCommunicationRange(Double.parseDouble(new String(ch,start,length)));
    				CommunicationRange = false;
    			}
    	 
    			if (SightRange) {
    				System.out.println("sightrange = " + new String(ch, start, length));
    				AgentImpl.agents.get(index).setSightRange(Double.parseDouble(new String(ch,start,length)));
    				SightRange = false;
    			}
    	 
    			if (MaxVelocity) {
    				System.out.println("maxvelocity = " + new String(ch, start, length));
    				AgentImpl.agents.get(index).setMaxVelocity(Double.parseDouble(new String(ch,start,length)));
    				MaxVelocity = false;
    			}
    			
    			if (MaxHeight) {
    				System.out.println("maxheight = " + new String(ch, start, length));
    				AgentImpl.agents.get(index).setMaxHeight(Double.parseDouble(new String(ch,start,length)));
    				MaxHeight = false;
    			}
    			
    			if (MaxBatteryTime) {
    				System.out.println("maxbattery = " + new String(ch, start, length));
    				AgentImpl.agents.get(index).setBatteryTime(Double.parseDouble(new String(ch,start,length)));
    				MaxBatteryTime = false;
    				//list.add(agent);
    			}
    	 
    		}
    	 
    	     };
    	 
    	       saxParser.parse("Agents.xml", handler);
    	 
    	     } catch (Exception e) {
    	       e.printStackTrace();
    	     }
    	 
    	//return list;
    }

 
    public static void main(String[] args) {
    	//System.out.println(java.);
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }
    
    /*@Override
    public void paintComponent(Graphics g) {
    	System.out.println(flag_map);
    	if(flag_map == true)
        g.drawImage(img,200,100,800,500,img.getMinX(),img.getMinY(),img.getWidth()+img.getMinX(),img.getHeight()+img.getMinY(), null); // see javadoc for more info on the parameters

    }*/

	@Override
	public void mouseClicked(MouseEvent arg0) {
        /*JComponent c = (JComponent) arg0.getSource();
        TransferHandler handler = c.getTransferHandler();
        handler.exportAsDrag(c, arg0, TransferHandler.COPY);*/
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		//System.out.println(arg0.getX());
		
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		//System.out.println(arg0.getX());
		
	}

	@Override
	public void mouseDragged(MouseEvent arg0) {
		if(arg0.getSource().equals(agentLabel)) {
        JComponent c = (JComponent) arg0.getSource();
        TransferHandler handler = c.getTransferHandler();
        handler.exportAsDrag(c, arg0, TransferHandler.COPY);
        dropx = posx;
        dropy = posy;
        //System.out.println(posx);
		//c.addMouseListener(this);
		}
	}

	@Override
	public void mouseMoved(MouseEvent arg0) {
		posx = arg0.getX();
		posy = arg0.getY();
        //System.out.println(posx);
	}
}